package com.kqb.minio.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.google.common.net.HttpHeaders;
import com.kqb.common.core.exception.ScException;
import com.kqb.common.core.utils.AjaxResult;
import com.kqb.minio.config.MinioProperties;
import io.minio.*;

import io.minio.errors.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

/**
 * @author 杉果树皮
 * @date 2025/4/15 17:26
 * @description:
 */
@RestController
@Api(tags = "文件上传下载")
@RequestMapping("/minio")
public class FileController {

    @Autowired
    MinioClient minioClient;

    @Autowired
    MinioProperties minioProperties;

    @PostConstruct
    public void init() {
        try {
            boolean b = minioClient.bucketExists(BucketExistsArgs.builder()
                    .bucket(minioProperties.getBucketName())
                    .build());

            if (!b) {
                minioClient.makeBucket(MakeBucketArgs.builder()
                        .bucket(minioProperties.getBucketName())
                        .build());

            }
        } catch (Exception e) {
            throw new ScException("创建minio桶失败");
        }

    }

    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public AjaxResult upload(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        if (!StrUtil.isNotBlank(originalFilename) || !originalFilename.contains(".")) {
            return AjaxResult.error("上传失败");
        }
        //判断是否存在
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //获取新的文件名
        String newFilename = IdUtil.simpleUUID() + suffix;
        String fileName = DateUtil.format(DateUtil.date(), "yyyyMMdd") + "/" + newFilename;
        try {
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(minioProperties.getBucketName())
                    .contentType(file.getContentType())
                    .stream(file.getInputStream(), file.getInputStream().available(), -1)
                    .object(fileName)
                    .build());
        } catch (Exception e) {
            throw new ScException("上传文件到minio失败");
        }
        return AjaxResult.success("文件上传成功", minioProperties.getUrl() + "/" + minioProperties.getBucketName() + "/" + fileName);
    }

    @GetMapping("/download")
    @ApiOperation("文件下载")
    public ResponseEntity<InputStreamResource> download(@RequestParam("url") String url) {
        String filename = url.split(minioProperties.getBucketName() + "/")[1];

        try {
            GetObjectArgs getObjectArgs = GetObjectArgs.builder()
                    .bucket(minioProperties.getBucketName())
                    .object(filename)
                    .build();
            InputStream inputStream = minioClient.getObject(getObjectArgs);
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + filename.split("/")[1])
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .body(new InputStreamResource(inputStream));
        } catch (Exception e) {
            throw new ScException("minio文件下载失败");
        }


    }


}
